<template>

    <el-card>
        <el-input placeholder="请输入部门名称" v-model="Search.DepartmentName" style="width: 200px;margin-right: 10px;" ></el-input>
        <el-button type="primary" @click="GetDepartmentList">查询</el-button>
        <el-button type="success" @click="openAddDialog" style="margin-left: 10px;">新增</el-button>
    </el-card>

    &nbsp;

    <el-card>


        <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed prop="DepartmentId" label="部门编号"  />
        <el-table-column fixed prop="DepartmentName" label="部门名称"  />
        <el-table-column prop="DepartmentStatus" label="状态"  >
            <template #default="scope">
                <el-tag v-if="scope.row.DepartmentStatus==0" type="success">启用</el-tag>
                <el-tag v-else type="danger">禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="PeopleNum" label="成员数量"  />
        <el-table-column prop="ManagerPeople" label="主管人员" />
        <el-table-column prop="DepartmentDesc" label="部门描述" />
        <el-table-column prop="UpdatedTime" label="更新时间"  >
            <template #default="scope">
                {{ moment(scope.row.UpdatedTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作列" min-width="120">
            <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
            </el-button>
            <el-button link type="primary" size="small" @click="handleSetStatus(scope.row)">设置状态</el-button>
            <el-button link type="primary" size="small" @click="DelDepartmentId(scope.row.DepartmentId)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>


        <el-pagination
        v-model:current-page="Search.PageIndex"
        v-model:page-size="Search.PageSize"
        :page-sizes="[10, 15, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Search.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />

    </el-card>

    <!-- 新增部门对话框 -->
    <el-dialog v-model="addDialogVisible" :title="isEdit ? '编辑部门' : '新建部门'" width="30%" @close="resetForm">
      <el-form :model="deptForm" label-width="100px">
        <el-form-item label="部门名称" required>
          <el-input v-model="deptForm.departmentName" placeholder="输入内容"></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader
            v-model="deptForm.parentDepartmentPath"
            :options="deptTreeData"
            :props="{ 
              checkStrictly: true,
              value: 'value',
              label: 'label',
              children: 'children',
              emitPath: false,
            }"
            placeholder="选择部门"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="主管人员" required>
          <div>
            <el-cascader
              v-model="deptForm.managerPeoplePath1"
              :options="peopleTreeData"
              :props="{ 
                checkStrictly: true,
                value: 'value',
                label: 'label',
                children: 'children',
                emitPath: false,
              }"
              placeholder="选择主管人员"
              clearable
              style="width: 100%;"
              @change="handleManagerCascaderChange"
            />
            <!-- 选择部门后显示该部门下的用户列表 -->
            <div v-if="selectedDeptUsers.length > 0" style="margin-top: 10px; max-height: 200px; overflow-y: auto; border: 1px solid #EBEEF5; border-radius: 4px; padding: 5px;">
              <el-radio-group v-model="deptForm.selectedUserId" @change="handleUserSelect">
                <div v-for="user in selectedDeptUsers" :key="user.value" style="margin: 5px 0; padding: 5px; border-bottom: 1px solid #EBEEF5;">
                  <el-radio :label="user.value">{{ user.label }}</el-radio>
                </div>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input v-model="deptForm.departmentDesc" type="textarea" placeholder="输入内容" :rows="4" maxlength="100" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="设置部门状态" width="30%" @close="resetStatusForm">
        <el-form :model="statusForm" label-width="100px">
            <el-form-item label="部门名称">
                <el-input v-model="statusForm.DepartmentName" disabled></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-radio-group v-model="statusForm.DepartmentStatus">
                    <el-radio :label="0">启用</el-radio>
                    <el-radio :label="1">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="statusDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveStatus(statusForm.DepartmentId)">保存</el-button>
            </span>
        </template>
    </el-dialog>

  </template>
  
  <script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { DepartmentList, DepartmentTreeSel, GetPeopleFromDepartment } from '@/api/Readapi';
import { DelDepartment, AddDepartment, UpdateDepartment, UpdateStatusDepartment } from '@/api/Writeapi';
import { ElMessageBox, ElMessage } from 'element-plus';
import moment from 'moment';

  //#region 部门列表
  
  const tableData = ref([]);

  const Search = reactive({
    PageIndex:1,
    PageSize:10,
    DepartmentName:'',
    TotalCount:0,
    TotalPage:0
  })

 const GetDepartmentList = async()=>{
    const res = await DepartmentList(Search) 

    tableData.value = res.data.data
    Search.TotalCount = res.data.TotalCount
    Search.TotalPage = res.data.TotalPage
 }

 const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  Search.PageSize=val;
  GetDepartmentList();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  Search.PageIndex=val;
  GetDepartmentList()
}

 onMounted(()=>{
    GetDepartmentList()
 })

 //#endregion 

 //#region 删除部门
 const DelDepartmentId = (id: any) => {
  ElMessageBox.confirm(
    '确定要删除该部门吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(async () => {
    await DelDepartment(id)
    ElMessage.success('删除成功')
    GetDepartmentList()
  })
  .catch(async() => {
    ElMessage.info('已取消删除')
  })
}
//#endregion

// #region 新增部门
const addDialogVisible = ref(false)
const deptTreeData = ref<any[]>([])
const peopleTreeData = ref<any[]>([])
const selectedDeptUsers = ref<any[]>([])
const isEdit = ref(false)

const deptForm = reactive({
  departmentName: '',
  parentDepartmentPath: [] as any[],
  PartneId: 0,
  managerPeoplePath1: [] as any[],
  managerPeopleValue: '',
  selectedUserId: '',
  managerPeople: '',
  departmentDesc: '',
  DepartmentId: 0,
  ManagerPeopleId: 0
})

//#region 获取部门树形数据
const getDeptTreeData = async () => {
  try {
    const res = await DepartmentTreeSel()

    if (res.data) {
      deptTreeData.value = res.data
    }
  } catch (error) {
    console.error('获取部门树形数据失败', error)
  }
}
//#endregion

// 获取部门人员树形数据
const getPeopleTreeData = async () => {
  try {
    const res = await GetPeopleFromDepartment()
    console.log('部门人员数据:', res)
    
    if (res.data) {
      peopleTreeData.value = res.data
    }
  } catch (error) {
    console.error('获取部门人员数据失败', error)
  }
}


// 处理用户选择
const handleUserSelect = (userId: any) => {
  // 根据选中的用户ID查找对应的用户信息
  const selectedUser = selectedDeptUsers.value.find(user => user.value === userId)
  if (selectedUser) {
    deptForm.managerPeople = selectedUser.label // 直接使用 label 作为 NickName
  }
}

const handleManagerCascaderChange = (val: any) => {
  deptForm.managerPeopleValue = val; // 存储主管人员value (ID)
  deptForm.ManagerPeopleId = Number(val); // 同时存储到ManagerPeopleId (确保是number)
  // 递归查找选中节点获取label (姓名)
  function findNodeByValue(tree: any[], value: any): any {
    for (const node of tree) {
      if (node.value === value) return node;
      if (node.children) {
        const found = findNodeByValue(node.children, value);
        if (found) return found;
      }
    }
    return null;
  }
  const selectedNode = findNodeByValue(peopleTreeData.value, val);
  if (selectedNode && selectedNode.label) {
    // 使用label作为提交的ManagerPeople (姓名)
    deptForm.managerPeople = selectedNode.label;
  } else {
    deptForm.managerPeople = '';
  }
}

const handleEdit = (row: any) => {
  isEdit.value = true;
  addDialogVisible.value = true;
  
  // 填充其他字段
  deptForm.departmentName = row.DepartmentName;
  deptForm.departmentDesc = row.DepartmentDesc;
  deptForm.DepartmentId = row.DepartmentId;

  // 回填上级部门 (将单个ID包装成数组)
  deptForm.parentDepartmentPath = row.ParentId

  // 回填主管人员 (获取value/ID并包装成数组回显)
  const managerId = row.ManagerPeopleId 
  deptForm.managerPeopleValue = managerId
  deptForm.ManagerPeopleId = managerId
  deptForm.managerPeoplePath1 = managerId 
  
  // 同时回填主管人员姓名 (如果后端提供 ManagerPeople 姓名)
  deptForm.managerPeople = row.ManagerPeople

  // 每次打开新增/编辑弹窗都重新获取树形数据，确保数据最新
  getDeptTreeData();
  getPeopleTreeData();
}

const handleSave = async () => {
  if (!deptForm.departmentName) {
    ElMessage.warning('请输入部门名称')
    return
  }
  // 检查主管人员value (ID) 是否已选择
  if (!deptForm.ManagerPeopleId) {
     ElMessage.warning('请选择主管人员')
     return
  }

    // 直接取上级部门的 value 作为 ParentId，类型为number
    let ParentId = 0;
    // emitPath: false 时，parentDepartmentPath[0] 就是选中的value
    if (deptForm.parentDepartmentPath && deptForm.parentDepartmentPath.length > 0) {
      ParentId = Number(deptForm.parentDepartmentPath[0]);
    }

    const data: any = {
      DepartmentName: deptForm.departmentName,
      ParentId: ParentId,
      DepartmentStatus: 0,
      PeopleNum: 100,
      ManagerPeople: deptForm.managerPeople,
      DepartmentDesc: deptForm.departmentDesc,
      ManagerPeopleId: deptForm.ManagerPeopleId
    }

    let res: any
    if (isEdit.value) {
      // 编辑时需要带上部门ID
      const updateData = { ...data, DepartmentId: deptForm.DepartmentId };
      res = await UpdateDepartment(updateData);
      if (res.code === 200) {
        ElMessage.success('修改成功')
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      // 新增时提交数据
      const addData = { ...data };
      res = await AddDepartment(addData);
      if (res.code === 200) {
        ElMessage.success('添加部门成功')
      } else {
        ElMessage.error(res.msg)
      }
    }
    addDialogVisible.value = false
    isEdit.value = false
    resetForm()
    GetDepartmentList()
  
}

const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  addDialogVisible.value = true
  getDeptTreeData()
  getPeopleTreeData()
}

const resetForm = () => {
  deptForm.departmentName = ''
  deptForm.parentDepartmentPath = [] as any[]
  deptForm.PartneId = 0
  deptForm.managerPeoplePath1 = [] as any[]
  deptForm.managerPeopleValue = ''
  deptForm.selectedUserId = ''
  deptForm.managerPeople = ''
  deptForm.departmentDesc = ''
  deptForm.DepartmentId = 0
  deptForm.ManagerPeopleId = 0
  selectedDeptUsers.value = []
}

// #region 设置部门状态
const statusDialogVisible = ref(false);
const statusForm = reactive({
    DepartmentId: 0,
    DepartmentName: '',
    DepartmentStatus: 0
});

const handleSetStatus = (row: any) => {
    statusForm.DepartmentId = row.DepartmentId;
    statusForm.DepartmentName = row.DepartmentName;
    statusForm.DepartmentStatus = row.DepartmentStatus;
    statusDialogVisible.value = true;
};

const resetStatusForm = () => {
    statusForm.DepartmentId = 0;
    statusForm.DepartmentName = '';
    statusForm.DepartmentStatus = 0; // 默认重置为启用
};

const saveStatus = async (id:any) => {
   
        const res: any = await UpdateStatusDepartment(id);
        if (res.code === 200) {
            ElMessage.success('状态更新成功');
            statusDialogVisible.value = false;
            GetDepartmentList();
        } else {
            ElMessage.error(res.msg);
        }
    
};
//#endregion

  </script>